import { useState, useCallback, useRef } from 'react';
import { ChatService } from '../services/chatService';
import { MESSAGE_TYPES, NODE_TYPES } from '../config/constants';

export const useChat = (sessionId) => {
    const [messages, setMessages] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [currentStreamData, setCurrentStreamData] = useState([]);
    const [hasMoreHistory, setHasMoreHistory] = useState(true);
    const [isGenerating, setIsGenerating] = useState(false); // AI是否正在生成回复
    const historyPagingRef = useRef({ lastCreateTime: '', pageSize: 10 });
    const currentRequestRef = useRef(null); // 当前请求的引用

    // 简单的时间排序测试函数
    const testMessageSorting = useCallback(() => {
        const testMessages = [
            { type: 'user', content: '最新消息', createTime: '2025-09-29 20:11:50' },
            { type: 'assistant', streamData: [], createTime: '2025-09-29 20:11:48' },
            { type: 'user', content: '最早消息', createTime: '2025-09-29 20:11:44' },
            { type: 'assistant', streamData: [], createTime: '2025-09-29 20:11:46' }
        ];

        const sorted = testMessages.sort((a, b) => {
            return new Date(a.createTime).getTime() - new Date(b.createTime).getTime();
        });

        let isCorrect = true;
        for (let i = 1; i < sorted.length; i++) {
            const prevTime = new Date(sorted[i - 1].createTime).getTime();
            const currTime = new Date(sorted[i].createTime).getTime();
            if (prevTime > currTime) {
                console.error('❌ 排序错误:', sorted[i - 1].createTime, '>', sorted[i].createTime);
                isCorrect = false;
            }
        }

        if (isCorrect) {
            console.log('✅ 时间排序测试通过');
        }
        return isCorrect;
    }, []);

    // 在开发环境下运行排序测试
    if (process.env.NODE_ENV === 'development') {
        console.log('🧪 运行时间排序测试...');
        testMessageSorting();
    }

    const addMessage = useCallback((message) => {
        setMessages(prev => [...prev, message]);
    }, []);

    // 添加欢迎消息
    const addWelcomeMessage = useCallback(() => {
        const welcomeMessage = {
            type: MESSAGE_TYPES.ASSISTANT,
            content: "您好！我是您的智能指标查询助手，我将帮您查询相关数据。",
            isWelcome: true // 标记为欢迎消息
        };
        setMessages([welcomeMessage]);
    }, []);

    // 时间排序工具函数 - 改进版本，支持messageId辅助排序
    const sortMessagesByTime = useCallback((messages, ascending = true) => {
        return messages.sort((a, b) => {
            const timeA = new Date(a.createTime);
            const timeB = new Date(b.createTime);

            // 检查时间是否有效
            const aValid = !isNaN(timeA.getTime());
            const bValid = !isNaN(timeB.getTime());

            if (!aValid && !bValid) {
                // 如果都没有有效时间，使用messageId排序
                const idA = a.messageId || 0;
                const idB = b.messageId || 0;
                return ascending ? idA - idB : idB - idA;
            }
            if (!aValid) return 1; // 无效时间排到后面
            if (!bValid) return -1;

            const timeDiff = timeA.getTime() - timeB.getTime();

            // 如果时间差小于1秒，使用messageId作为辅助排序
            if (Math.abs(timeDiff) < 1000) {
                const idA = a.messageId || 0;
                const idB = b.messageId || 0;
                console.log(`⏰ 时间相近，使用messageId排序: ${a.createTime} (${idA}) vs ${b.createTime} (${idB})`);
                return ascending ? idA - idB : idB - idA;
            }

            return ascending ? timeDiff : -timeDiff;
        });
    }, []);

    // 验证消息时间顺序
    const validateTimeOrder = useCallback((messages) => {
        console.log('🕒 验证消息时间顺序:');
        for (let i = 1; i < messages.length; i++) {
            const prevTime = new Date(messages[i - 1].createTime);
            const currTime = new Date(messages[i].createTime);

            if (!isNaN(prevTime.getTime()) && !isNaN(currTime.getTime())) {
                if (prevTime > currTime) {
                    console.warn(`⚠️ 时间顺序错误: ${messages[i - 1].createTime} > ${messages[i].createTime}`);
                } else {
                    console.log(`✅ 时间顺序正确: ${messages[i - 1].createTime} <= ${messages[i].createTime}`);
                }
            }
        }
    }, []);

    // 消息去重函数 - 改进版本，使用更精确的唯一标识
    const deduplicateMessages = useCallback((messages) => {
        const seen = new Set();
        return messages.filter(message => {
            // 为每个消息创建更精确的唯一标识符
            let key;
            if (message.createTime) {
                // 使用时间+类型+内容的部分哈希作为键，避免时间相同的误判
                const contentPreview = message.type === MESSAGE_TYPES.USER ?
                    message.content?.substring(0, 50) || '' :
                    JSON.stringify(message.streamData || message.content).substring(0, 100);
                key = `${message.createTime}-${message.type}-${contentPreview}`;
            } else {
                // 如果没有createTime，使用内容哈希
                const contentHash = message.type === MESSAGE_TYPES.USER ?
                    message.content :
                    JSON.stringify(message.streamData || message.content);
                key = `${message.type}-${contentHash}`;
            }

            if (seen.has(key)) {
                console.log('发现重复消息，已过滤:', key.substring(0, 100) + '...');
                return false;
            }
            seen.add(key);
            return true;
        });
    }, []);

    // 停止AI生成
    const stopGeneration = useCallback(async () => {
        if (!sessionId || !isGenerating) return;

        try {
            console.log('🛑 用户请求停止生成');
            await ChatService.stopGeneration(sessionId);
            
            // 取消当前请求
            if (currentRequestRef.current) {
                currentRequestRef.current.abort();
                currentRequestRef.current = null;
            }
            
            setIsLoading(false);
            setIsGenerating(false);
            setCurrentStreamData([]);
            
            console.log('✅ 生成已停止');
        } catch (error) {
            console.error('停止生成失败:', error);
        }
    }, [sessionId, isGenerating]);

    const sendMessage = useCallback(async (query) => {
        if (!query.trim() || !sessionId) return;

        // 防止重复提交：如果正在生成回复，则拒绝新请求
        if (isGenerating || isLoading) {
            console.warn('⚠️ AI正在生成回复，请等待完成后再发送新消息');
            return;
        }

        // 添加用户消息
        const userMessage = {
            type: MESSAGE_TYPES.USER,
            content: query
        };
        addMessage(userMessage);

        setIsLoading(true);
        setIsGenerating(true);
        setCurrentStreamData([]);

        // 创建AbortController用于取消请求
        const abortController = new AbortController();
        currentRequestRef.current = abortController;

        try {
            console.log('🚀 开始AI生成，sessionId:', sessionId);
            const response = await ChatService.sendMessage(query, sessionId);
            const streamDataCollector = [];

            // 处理流式响应
            for await (const data of ChatService.processStreamResponse(response)) {
                // 检查是否被取消
                if (abortController.signal.aborted) {
                    console.log('🛑 请求已被取消');
                    return;
                }
                
                streamDataCollector.push(...data);
                setCurrentStreamData([...streamDataCollector]);
            }

            // 检查是否被取消
            if (abortController.signal.aborted) {
                console.log('🛑 请求已被取消');
                return;
            }

            // 添加助手消息
            const assistantMessage = {
                type: MESSAGE_TYPES.ASSISTANT,
                streamData: streamDataCollector
            };
            addMessage(assistantMessage);
            console.log('✅ AI生成完成');

        } catch (error) {
            // 如果是取消操作，不显示错误
            if (error.name === 'AbortError' || abortController.signal.aborted) {
                console.log('🛑 请求被用户取消');
                return;
            }

            console.error('发送消息失败:', error);
            const errorMessage = {
                type: MESSAGE_TYPES.ASSISTANT,
                streamData: [{
                    node: NODE_TYPES.ERROR,
                    data: { result: '请求失败，请检查网络连接' }
                }]
            };
            addMessage(errorMessage);
        } finally {
            setIsLoading(false);
            setIsGenerating(false);
            setCurrentStreamData([]);
            currentRequestRef.current = null;
        }
    }, [addMessage, sessionId, isGenerating, isLoading]);

    const clearMessages = useCallback(() => {
        setCurrentStreamData([]);
        // 重置分页信息
        const newPaging = { lastCreateTime: '', pageSize: 10 };
        historyPagingRef.current = newPaging;
        setHasMoreHistory(true);
        // 清理后添加欢迎消息
        addWelcomeMessage();
    }, [addWelcomeMessage]);

    // 仅清空消息，不添加欢迎消息
    const clearMessagesOnly = useCallback(() => {
        setMessages([]);
        setCurrentStreamData([]);
        // 重置分页信息
        const newPaging = { lastCreateTime: '', pageSize: 10 };
        historyPagingRef.current = newPaging;
        setHasMoreHistory(true);
    }, []);

    const mapHistoryRecordToMessage = (record) => {
        console.log('处理历史记录:', { role: record.role, createTime: record.createTime });

        if (record.role === 'user') {
            const userMessage = {
                type: MESSAGE_TYPES.USER,
                content: record.content,
                createTime: record.createTime,
                messageId: record.messageId // 保留messageId用于排序
            };
            console.log('映射用户消息:', userMessage);
            return userMessage;
        }
        if (record.role === 'assistant') {
            // content 可能为对象，取 data 数组作为渲染流节点
            const streamData = record.content && record.content.data ? record.content.data : [];
            const assistantMessage = {
                type: MESSAGE_TYPES.ASSISTANT,
                streamData,
                createTime: record.createTime,
                messageId: record.messageId, // 保留messageId用于排序
                // 如果streamData为空，保存原始content用于备用显示
                originalContent: record.content
            };
            console.log('映射AI消息:', {
                ...assistantMessage,
                streamData: streamData.length + ' items',
                hasOriginalContent: !!record.content,
                messageId: record.messageId
            });
            return assistantMessage;
        }
        console.log('未知角色，跳过:', record.role);
        return null;
    };

    const loadHistory = useCallback(async (targetSessionId, loadMore = false) => {
        const sid = targetSessionId || sessionId;
        if (!sid) {
            console.warn('⚠️ loadHistory: 无效的sessionId');
            return;
        }

        try {
            const pageSize = 10; // 每次只加载10条
            const lastCreateTime = loadMore ? historyPagingRef.current.lastCreateTime : '';

            console.log('🔍 加载历史记录:', {
                sessionId: sid,
                pageSize,
                lastCreateTime,
                loadMore,
                currentPaging: historyPagingRef.current,
                requestTime: new Date().toISOString(),
                explanation: loadMore
                    ? `加载更多：获取早于 ${lastCreateTime} 的 ${pageSize} 条记录`
                    : `首次加载：获取最新的 ${pageSize} 条记录`
            });

            const { records, total } = await ChatService.getHistory({
                sessionId: sid,
                pageSize: pageSize,
                lastCreateTime: lastCreateTime
            });

            // 防御性检查：确保返回的数据不为空且是数组
            if (!records || !Array.isArray(records)) {
                console.warn('⚠️ API返回的records无效:', records);
                return;
            }

            // 如果返回空数组，直接返回，不进行后续处理
            if (records.length === 0) {
                console.log('📭 历史记录为空，不进行处理');
                if (!loadMore) {
                    // 首次加载且为空，清空消息列表
                    setMessages([]);
                }
                setHasMoreHistory(false);
                return;
            }

            console.log('📦 历史记录返回:', {
                recordsCount: records.length,
                total,
                loadMore,
                records: records.map((r, index) => ({
                    index,
                    createTime: r.createTime,
                    role: r.role,
                    content: typeof r.content === 'string' ? r.content.substring(0, 50) + '...' : r.content
                }))
            });

            // 对于基于时间的分页，API返回的记录应该已经是按时间排序的
            // 首次查询返回最新的记录，后续查询返回更早的记录
            console.log('原始记录顺序:', records.map((r, index) => ({
                index,
                createTime: r.createTime,
                role: r.role
            })));

            const mapped = records
                .map((record, index) => {
                    console.log(`映射记录 ${index}:`, {
                        role: record.role,
                        createTime: record.createTime,
                        content: typeof record.content === 'string' ? record.content.substring(0, 50) + '...' : record.content
                    });
                    return mapHistoryRecordToMessage(record);
                })
                .filter(Boolean);

            console.log('映射后的消息:', mapped.map((m, index) => ({
                index,
                type: m.type,
                createTime: m.createTime,
                hasContent: !!m.content,
                hasStreamData: !!m.streamData,
                content: m.type === 'user' ? m.content?.substring(0, 30) + '...' : 'AI回复'
            })));

            console.log('去重前消息数量:', mapped.length);
            const deduplicated = deduplicateMessages(mapped);
            console.log('去重后消息数量:', deduplicated.length);
            console.log('去重后的消息类型:', deduplicated.map(m => m.type));

            if (loadMore) {
                // 加载更多（更早的消息）时，按时间从旧到新排序后添加到消息列表开头
                console.log('🔄 加载更多时排序前:', deduplicated.map(m => ({
                    createTime: m.createTime,
                    type: m.type,
                    parsedTime: new Date(m.createTime).toISOString(),
                    isValidDate: !isNaN(new Date(m.createTime).getTime())
                })));

                const sortedMapped = sortMessagesByTime([...deduplicated], true); // 按时间升序排序（旧到新）

                console.log('🔄 加载更多时排序后:', sortedMapped.map(m => ({
                    createTime: m.createTime,
                    type: m.type,
                    parsedTime: new Date(m.createTime).toISOString()
                })));

                setMessages(prev => {
                    const combined = [...sortedMapped, ...prev];
                    return deduplicateMessages(combined);
                });

                // 更新分页信息和状态
                if (records.length > 0) {
                    // 获取当前批次中最早的消息时间，用于下次分页
                    // 对于基于时间的分页，我们需要找到时间最早的记录
                    const earliestRecord = records.reduce((earliest, current) => {
                        return new Date(current.createTime) < new Date(earliest.createTime) ? current : earliest;
                    });

                    const newPaging = {
                        ...historyPagingRef.current,
                        lastCreateTime: earliestRecord.createTime
                    };
                    historyPagingRef.current = newPaging;

                    console.log('🔄 分页信息更新 (loadMore):', {
                        ...newPaging,
                        earliestRecordTime: earliestRecord.createTime,
                        recordsCount: records.length
                    });

                    // 检查是否还有更多历史记录
                    setHasMoreHistory(records.length === pageSize);
                } else {
                    setHasMoreHistory(false);
                }
            } else {
                // 首次加载，显示最新的消息，按时间从旧到新排序显示
                console.log('📅 首次加载排序前:', deduplicated.map(m => ({
                    createTime: m.createTime,
                    type: m.type,
                    parsedTime: new Date(m.createTime).toISOString(),
                    isValidDate: !isNaN(new Date(m.createTime).getTime())
                })));

                const sortedMapped = sortMessagesByTime([...deduplicated], true); // 按时间升序排序（旧到新）

                console.log('📅 首次加载排序后:', sortedMapped.map(m => ({
                    createTime: m.createTime,
                    type: m.type,
                    parsedTime: new Date(m.createTime).toISOString()
                })));

                // 直接设置历史记录，不添加欢迎消息
                // 欢迎消息已经通过clearMessages()在会话切换时添加了
                console.log('设置消息:', sortedMapped.map(m => ({ type: m.type, createTime: m.createTime })));
                validateTimeOrder(sortedMapped);
                setMessages(sortedMapped);

                // 设置分页信息，用于加载更早的消息
                if (records.length > 0) {
                    // 获取当前批次中最早的消息时间
                    const earliestRecord = records.reduce((earliest, current) => {
                        return new Date(current.createTime) < new Date(earliest.createTime) ? current : earliest;
                    });

                    const newPaging = {
                        lastCreateTime: earliestRecord.createTime,
                        pageSize: 10
                    };
                    historyPagingRef.current = newPaging;

                    console.log('🔄 首次加载分页信息:', {
                        ...newPaging,
                        earliestRecordTime: earliestRecord.createTime,
                        recordsCount: records.length
                    });

                    // 检查是否还有更多历史记录
                    setHasMoreHistory(records.length === pageSize);
                } else {
                    const newPaging = {
                        lastCreateTime: '',
                        pageSize: 10
                    };
                    historyPagingRef.current = newPaging;
                    setHasMoreHistory(false);
                }
            }
        } catch (e) {
            console.error('加载历史失败:', e);
        }
    }, [sessionId]);

    const loadMoreHistory = useCallback(() => {
        if (!hasMoreHistory) {
            console.log('⚠️ 没有更多历史记录了');
            return Promise.resolve();
        }
        return loadHistory(sessionId, true);
    }, [loadHistory, sessionId, hasMoreHistory]);

    return {
        messages,
        isLoading,
        isGenerating,
        currentStreamData,
        sendMessage,
        stopGeneration,
        clearMessages,
        clearMessagesOnly,
        loadHistory,
        loadMoreHistory,
        hasMoreHistory,
    };
};